package cn.edu.ctbu.studentweb.restcontroller;

import cn.edu.ctbu.studentweb.domain.Student;
import cn.edu.ctbu.studentweb.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {
    @Autowired
    StudentService studentService;
    @GetMapping("list")

    public List<Student> GetAll(){
        return studentService.findAll();
    }
    /**
     * 示例：　
     * 其中，2表示id
     * @param id
     * @return
     * **/
    @GetMapping(value="{id}")
    public Student GetById(@PathVariable Integer id){

        return studentService.findById(id);
    }
    /**
     * 示例：　
     *读取的ｕｒｌ：／ｗｅｂａｐｉ／ｓｔｕｄｅｎｔ／ｇｅｔ／ｉｄ
     * **/
    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable Integer id){

        Student student=studentService.getById(id);
        student.setPassword("");
        return student;
    }
    /**
     * uodate
     */


    @PutMapping("/update")
    public ResponseEntity<Student> update(@RequestBody Student student) {
        Student existingStudent = studentService.getById(student.getId());
        System.out.println("測試"+existingStudent);
        if (existingStudent == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        existingStudent.setName(student.getName()); // 更新名字
        existingStudent.setSex(student.getSex()); // 更新性别
        existingStudent.setScore(student.getScore()); // 更新成绩
        existingStudent.setNum(student.getNum()); // 更新学号
        existingStudent.setPassword(student.getPassword()); // 更新密码
        existingStudent.setAge(student.getAge()); // 更新年龄
        Student updatedStudent = StudentService.update(existingStudent);
        return new ResponseEntity<>(updatedStudent, HttpStatus.OK);
    }

    /**
     * 新增学生
     */
    @PostMapping("/insert")
    public Student insert(Student student){
        Student student1=studentService.insert(student);
        return student1;
    }
    @DeleteMapping(value="delete/{id}")
    public boolean DeleteById(@PathVariable Integer id){
        studentService.delete(id);
        return true;
    }
}

